<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryParams" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单编号" prop="number">
        <el-input
          v-model="queryParams.number"
          placeholder="请输入编号"
          clearable
          @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="订单状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" filterable clearable>
          <el-option label="待审核" value="0"></el-option>
          <el-option label="通过" value="1"></el-option>
          <el-option label="驳回" value="2"></el-option>
          <el-option label="已支付" value="5"></el-option>
          <el-option label="服务中" value="3"></el-option>
          <el-option label="已完成" value="4"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="预约日期" prop="appointmentDate">
        <el-date-picker
          clearable
          v-model="queryParams.appointmentDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择预约日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetForm('queryParams')">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDeleteList">
          删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport">
          导出
        </el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="tableData" ref="tableRef" @selection-change="handleSelectionChange">
      <el-table-column type="selection" fixed width="55" align="center"/>
      <el-table-column label="ID" align="center" fixed prop="id" width="70" :show-overflow-tooltip='true'/>
      <el-table-column label="连锁店" align="center" prop="staff.name" min-width="120" :show-overflow-tooltip='true'/>
      <el-table-column label="订单编号" align="center" prop="number" min-width="120" :show-overflow-tooltip='true'/>
      <el-table-column label="服务项目" align="center" prop="services.name" min-width="120" :show-overflow-tooltip='true'/>
      <el-table-column label="服务价格" align="center" prop="money" min-width="120" :show-overflow-tooltip='true'/>
      <el-table-column label="预约用户" align="center" prop="user.name" min-width="120" :show-overflow-tooltip='true'/>
      <el-table-column label="预约日期" align="center" prop="appointmentDate" min-width="120" :show-overflow-tooltip='true'/>
      <el-table-column label="预约事项" align="center" prop="matter" min-width="120" :show-overflow-tooltip='true'/>
      <el-table-column label="具体描述" align="center" prop="describes" min-width="120" :show-overflow-tooltip='true'/>
      <el-table-column label="订单状态" align="center" prop="status" min-width="100" :show-overflow-tooltip='true'>
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 0" :type="'info'" disable-transitions>待审核</el-tag>
          <el-tag v-if="scope.row.status === 1" :type="'primary'" disable-transitions>通过</el-tag>
          <el-tag v-if="scope.row.status === 2" :type="'success'" disable-transitions>驳回</el-tag>
          <el-tag v-if="scope.row.status === 5" :type="'danger'" disable-transitions>已支付</el-tag>
          <el-tag v-if="scope.row.status === 3" :type="'warning'" disable-transitions>服务中</el-tag>
          <el-tag v-if="scope.row.status === 4" :type="'danger'" disable-transitions>已完成</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="审核意见" align="center" prop="opinion" min-width="120" :show-overflow-tooltip='true'/>
      <el-table-column label="操作" align="center" fixed="right" width="100" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      layout="total, sizes, prev, pager, next, jumper"
      background
      v-show="total>0"
      :total="total"
      :current-page="queryParams.page"
      :page-size="queryParams.limit"
      :page-sizes="[10, 20, 30, 50]"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange">
    </el-pagination>

    <!-- 对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
        <el-form-item label="审核结果" prop="status">
          <el-radio v-model="form.status" label="1">通过</el-radio>
          <el-radio v-model="form.status" label="2">驳回</el-radio>
        </el-form-item>
        <el-form-item label="审核意见" prop="opinion">
          <el-input v-model="form.opinion" placeholder="请输入审核意见" clearable/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="submitForm">确 定</el-button>
        <el-button size="small" @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import {
    dataAppointment,
    dynamicListAppointment,
    listLimitAppointment,
    countAppointment,
    dynamicCountAppointment,
    allAppointment,
    getAppointment,
    detailsGetAppointment,
    dynamicGetAppointment,
    addAppointment,
    editAppointment,
    delAppointment,
    delListAppointment
  } from '@/api/appointment'
  import { allServices } from '@/api/services'
  import { listFieldUser } from '@/api/user'

  export default {
    name: 'Appointment',
    computed: {
      ...mapGetters([
        'userId'
      ])
    },
    data() {
      // 表单数据空值效验
      const validateData = (rule, value, callback) => {
        if (value == null || value.length == 0) {
          callback(new Error('必填项不能为空'))
        } else {
          callback()
        }
      }
      // 表单数据数字效验
      const validateNumberData = (rule, value, callback) => {
        if (value == null || value.length == 0) {
          callback(new Error('必填项不能为空'))
        } else {
          if (Number.isInteger(value)) {
            callback()
          } else {
            callback(new Error('请输入数字'))
          }
        }
      }
      return {
        servicesList: [],
        userList: [],
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 表格数据
        tableData: [],
        // 弹出层标题
        title: '',
        // 是否显示弹出层
        open: false,
        open2: false,
        // 查询参数
        queryParams: {
          page: 1,
          limit: 10,
          servicesId: null,
          userId: null,
          appointmentDate: null,
          matter: null,
          status: null,
          creatDate: null,
          staffId: null,
          number: null
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          id: [{ required: true, trigger: 'blur', validator: validateNumberData }],
          servicesId: [{ required: true, trigger: 'blur', validator: validateNumberData }],
          userId: [{ required: true, trigger: 'blur', validator: validateNumberData }],
          appointmentDate: [{ required: true, trigger: 'blur', validator: validateData }],
          matter: [{ required: true, trigger: 'blur', validator: validateData }],
          describes: [{ required: true, trigger: 'blur', validator: validateData }],
          status: [{ required: true, trigger: 'blur', validator: validateData }],
          opinion: [{ required: true, trigger: 'blur', validator: validateData }],
          year: [{ required: true, trigger: 'blur', validator: validateNumberData }],
          month: [{ required: true, trigger: 'blur', validator: validateNumberData }],
          creatDate: [{ required: true, trigger: 'blur', validator: validateData }],
          staffId: [{ required: true, trigger: 'blur', validator: validateNumberData }],
          number: [{ required: true, trigger: 'blur', validator: validateData }]
        }
      }
    },
    created() {
      this.getData()
      this.allServices()
      this.listFieldUser()
    },
    watch: {
      '$route': 'getData'
    },
    methods: {
      allServices() {
        this.loading = true
        allServices().then(response => {
          this.servicesList = response.data
          this.loading = false
        })
      },
      listFieldUser() {
        this.loading = true
        listFieldUser("role", 1).then(response => {
          this.userList = response.data
          this.loading = false
        })
      },
      /** 查询分页数据 */
      getData() {
        this.loading = true
        dataAppointment(this.queryParams).then(response => {
          this.tableData = response.data
          this.total = response.count
          this.loading = false
        })
      },
      // 分页数据条数监听
      handleSizeChange(val) {
        this.loading = true
        this.queryParams.limit = val
        this.getData()
      },
      // 分页数据跳转监听
      handleCurrentChange(val) {
        this.loading = true
        this.queryParams.page = val
        this.getData()
      },
      // 搜索按钮操作
      handleQuery() {
        this.queryParams.page = 1
        this.getData()
      },
      // 重置按钮操作
      resetForm(formName) {
        this.$nextTick(() => {
          this.$refs[formName].resetFields()
        })
        this.handleQuery()
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      // 取消按钮
      cancel() {
        this.open = false
        this.open2 = false
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          servicesId: null,
          userId: null,
          appointmentDate: null,
          matter: null,
          describes: null,
          status: null,
          opinion: null,
          year: null,
          month: null,
          creatDate: null,
          staffId: null,
          number: null
        }
        this.$nextTick(() => {
          this.$refs['form'].clearValidate()
        })
      },
      /** 编辑按钮操作 */
      handleUpdate(row) {
        this.form.id = row.id
        this.open = true
        this.title = '预约审核'
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs['form'].validate(valid => {
          if (valid) {
            editAppointment(this.form).then(response => {
              this.$message.success('操作成功')
              this.open = false
              this.getData()
            })
          }
        })
      },
      // 单个删除按钮操作
      handleDelete(row) {
        this.$confirm('确定删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          return delAppointment(row.id)
        }).then(() => {
          this.getData()
          this.$message.success('删除成功')
        }).catch(() => {
        })
      },
      // 批量删除按钮操作
      handleDeleteList(row) {
        this.$confirm('确定删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          return delListAppointment(this.ids)
        }).then(() => {
          this.getData()
          this.$message.success('删除成功')
        }).catch(() => {
        })
      },
      // 导出表格
      handleExport() {
        import('@/vendor/Export2Excel').then(excel => {
          // 表格名称
          const columnNames = ['预约订单ID', '服务项目ID', '用户ID', '预约日期', '预约事项', '具体描述', '审核状态', '审核意见', '年份', '月份', '创建日期', '连锁店ID', '编号']
          // 表格属性
          const headerProps = ['id', 'servicesId', 'userId', 'appointmentDate', 'matter', 'describes', 'status', 'opinion', 'year', 'month', 'creatDate', 'staffId', 'number']
          // 表格数据
          allAppointment().then(response => {
            const formatData = response.data
            const data = this.formatJson(headerProps, formatData)
            excel.export_json_to_excel({
              header: columnNames,
              data,
              filename: this.filename,
              autoWidth: this.autoWidth,
              bookType: this.bookType
            })
          })
        })
      },
      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        }))
      }
    }
  }
</script>
